var serverUrl = "ws://localhost:81";
var extDrawTouchEvent = true;
var extDrawGestures = true;
var tabinfo = {};

function unactivateButton(tabId)
{
	tabinfo[tabId]["chrome_button_active"] = false;
	chrome.browserAction.setIcon({tabId: tabId, path: 'images/icon-19-disabled.png'});
	chrome.browserAction.setTitle({tabId: tabId, title: 'Forcepad Disabled'});
	chrome.tabs.executeScript(tabId, {code:'getClientRequest({data:{"method":"disconnect","user":""}});'});
	console.debug('off '+tabId);
}

function activateButton(tabId)
{
	tabinfo[tabId]["chrome_button_active"] = true;
	chrome.browserAction.setIcon({tabId: tabId, path: 'images/icon-19-enabled.png'});
	chrome.browserAction.setTitle({tabId: tabId, title: 'Forcepad Enabled'});
	chrome.tabs.executeScript(tabId, {code:'getClientRequest({data:{"method":"connect","url":"'+serverUrl+'","user":""}});'});
	console.debug('on '+tabId);
}

chrome.browserAction.onClicked.addListener(function(tab) {
	if(typeof tabinfo[tab.id] != 'undefined')
	{
		if(tabinfo[tab.id]["chrome_button_active"])
		{
			unactivateButton(tab.id);
		}
		else
		{
			activateButton(tab.id);
		}
	}
	else
	{
		tabinfo[tab.id] = {};
		chrome.tabs.executeScript(tab.id, {file:"clientSocket.js"});
		if(extDrawTouchEvent)
		{
			chrome.tabs.insertCSS(tab.id, {file:"extDrawTouchEvent.css"});
			chrome.tabs.executeScript(tab.id, {file:"extDrawTouchEvent.js"});
		}
		if(extDrawGestures)
		{
			chrome.tabs.executeScript(tab.id, {file:"quo.js"});
			chrome.tabs.executeScript(tab.id, {file:"extDrawGestures.js"});
		}
		activateButton(tab.id);
	}
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	if(typeof tabinfo[tabId] != 'undefined')
	{
		unactivateButton(tabId);
		delete tabinfo[tabId];
	}
});

chrome.tabs.onRemoved.addListener(function(tabId){
	if(typeof tabinfo[tabId] != 'undefined')
	{
		delete tabinfo[tabId];
	}
});